package utils

import (
	"crypto/md5"
	"encoding/hex"
	"encoding/json"
	"strings"

	"hass.tree.com/bridge/sysConfig"
)

type SmsBatchObject struct {
	Mobiles []string `json:"mobiles"`
	Content string   `json:"content"`
}

type SmsSingleObject struct {
	Mobile  string `json:"mobile"`
	Content string `json:"content"`
}

type SmsMultiObject struct {
	SmsSingles []SmsSingleObject `json:"smsObjects"`
}

func SendSmsMessageBatch(SmsBatchObject SmsBatchObject) string {
	data := make(map[string]interface{})
	data["action"] = "send"
	data["account"] = sysConfig.AllConfig.Sms.Account
	data["extno"] = sysConfig.AllConfig.Sms.Extno
	data["label"] = ""
	data["mobileEencryptionMode"] = ""
	mobiles := ""
	for k, mobile := range SmsBatchObject.Mobiles {
		if k == 0 {
			mobiles += mobile
		} else {
			mobiles += "," + mobile
		}
	}
	md5Password := sysConfig.AllConfig.Sms.Password + sysConfig.AllConfig.Sms.Extno + mobiles + SmsBatchObject.Content
	data["mobile"] = mobiles
	sum := md5.Sum([]byte(md5Password))
	md5String := hex.EncodeToString(sum[:])
	data["password"] = strings.ToUpper(md5String)
	data["content"] = SmsBatchObject.Content
	return PostJson(sysConfig.AllConfig.Sms.Url, data)
}

func SendSmsMessageMulti(smsMultiObject SmsMultiObject) string {
	data := make(map[string]interface{})

	data["action"] = "p2p"
	data["account"] = sysConfig.AllConfig.Sms.Account
	data["extno"] = sysConfig.AllConfig.Sms.Extno
	data["label"] = ""
	data["mobileEencryptionMode"] = ""
	mobileContent := "{"
	passwordUncode := sysConfig.AllConfig.Sms.Password + sysConfig.AllConfig.Sms.Extno
	for k, smsSingle := range smsMultiObject.SmsSingles {
		if k == 0 {
			mobileContent += "\"" + smsSingle.Mobile + "\":\"" + smsSingle.Content + "\""
		} else {
			mobileContent += ",\"" + smsSingle.Mobile + "\":\"" + smsSingle.Content + "\""
		}
		passwordUncode += smsSingle.Mobile + smsSingle.Content
	}
	mobileContent += "}"

	sum := md5.Sum([]byte(passwordUncode))
	md5String := strings.ToUpper(hex.EncodeToString(sum[:]))
	data["password"] = md5String
	data["mobileContentKvp"] = "MOBILECONTENT_STR"

	dataBytes, _ := json.Marshal(data)
	dataString := string(dataBytes)
	dataString = strings.ReplaceAll(dataString, "\"MOBILECONTENT_STR\"", mobileContent)
	return PostJsonString(sysConfig.AllConfig.Sms.Url, dataString)
}
